﻿Imports Kairyu.Connection

Namespace Save

    ''' <summary>
    ''' 主キー書き込みクラス
    ''' </summary>
    ''' <remarks></remarks>
    Public Class KeyWriter

        Public Sub SetKeyOnPreviousSave(r As ModelSaver, def As SaveDefinition)
            If def.SaveType <> SaveType.Create Then Return

            '主キー列を取得
            Dim cols As IEnumerable(Of ColumnAttribute) = (From el In ColumnAttributeReader.ReadPrimaryKeys(def.TableAttribute.ModelType))

            For Each col As ColumnAttribute In cols
                Dim cmd As IDbCommand = col.Key.CreateKeyQueryBeforeSave(r.Transaction)
                If cmd Is Nothing Then Continue For

                Dim key As Object = cmd.ExecuteScalarWithLog(InfoLevelEnum.Debug)
                col.SetValue(def.Model, key)
            Next
        End Sub

        Public Sub SetKeyOnAfterSave(r As ModelSaver, def As SaveDefinition)
            If def.SaveType <> SaveType.Create Then Return
            If def.TableAttribute.IsRootBase = False Then Return '基底テーブル以外は処理しません

            '主キー列を取得
            Dim cols As IEnumerable(Of ColumnAttribute) = (From el In ColumnAttributeReader.ReadPrimaryKeys(def.TableAttribute.ModelType))

            For Each col As ColumnAttribute In cols
                Dim cmd As IDbCommand = col.Key.CreateKeyQueryAfterSave(r.Transaction)
                If cmd Is Nothing Then Continue For

                Dim key As Object = cmd.ExecuteScalarWithLog(InfoLevelEnum.Debug)
                col.SetValue(def.Model, key)
            Next
        End Sub

    End Class

End Namespace

